package com.yljk.yljkproject.ui.webview;

import android.content.Context;
import android.os.Build;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.RequiresApi;

import com.yilijk.base.network.error.HttpErrorUtils;
import com.yilijk.base.utils.ALog;
import com.yljk.yljkproject.utils.PushMessageUtil;

/**
 * Created by SHICHENG
 * <p>
 * Time on
 */
public class ArticleWebViewClient extends WebViewClient {

    Context context;

    public ArticleWebViewClient(Context context) {
        this.context = context;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        //重置webview中img标签的图片大小
        imgReset(view);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith("com.doctor.scheme")){
            PushMessageUtil.getInstance().dealMessage(context,url,false);
        }else{
            view.loadUrl(url);
        }
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
        ALog.e(errorResponse.getStatusCode()+"");
        if (errorResponse.getStatusCode() == 401){
            HttpErrorUtils.switchCode(401);
        }
        super.onReceivedHttpError(view, request, errorResponse);

    }


    /**
     * 对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
     *
     * @param view*/
    private void imgReset(WebView view) {
        view.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var img = objs[i];   " +
                "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " +
                "}" +
                "})()");
    }
}
